package com.bnq.control.desktop.utils;

import android.content.Context;
import android.graphics.Bitmap;

import com.oray.commonutils.utils.CloseUtils;
import com.oray.commonutils.utils.LogUtil;
import com.oray.sunlogin.manager.util.BitmapOperationUtils;
import com.oray.sunlogin.manager.util.FileOperationUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ScreenShotUtils {

    private static final String TAG = ScreenShotUtils.class.getSimpleName();


    /**
     * 截屏保存图片
     *
     * @param bitmap
     */
    public static void screenShot(Context context, Bitmap bitmap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.getDefault());
        String sdPath = SDCardUtils.getSdCardPath(context).sdPath;
        String path = sdPath + File.separator + FileOperationUtils.getParentFileName() + File.separator + "picture" + File.separator;
        String filename = sdf.format(new Date()) + ".jpg";
        File file = new File(path, filename);
        if (!file.exists()) file.getParentFile().mkdirs();
        if (null != bitmap && !bitmap.isRecycled()) {
            LogUtil.i(TAG, "bitmap got!");
            saveBitmap(context, bitmap, file);
        } else {
            LogUtil.e(TAG, "bitmap is NULL!");
        }
    }

    /**
     * 保存图片并且更新相册
     */
    private static void saveBitmap(Context context, Bitmap bitmap, File file) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
            BitmapOperationUtils.addImage(context, context.getContentResolver(), file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeQuietly(fos);
        }
    }

}
